<template>
  <div ref="chart" style="width: 650px; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'StackedBarChart',
  props: {
    chartData: {
      type: Array,
      required: true,
      validator: value => value.every(item =>
          item.name &&
          Array.isArray(item.data)
      )
    },
    xAxisLabels: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      myChart: null
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  watch: {
    chartData: {
      handler() {
        this.refreshChart();
      },
      deep: true
    },
    xAxisLabels() {
      this.refreshChart();
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chart;
      this.myChart = echarts.init(chartDom);
      this.setChartOption();
    },
    setChartOption(){
      const totalData = Array(this.chartData[0]?.data?.length || 0).fill(0);
      this.chartData.forEach(item => {
        item.data.forEach((value, index) => {
          totalData[index] += Number(value); // 确保数值类型
        });
      });

      // 四舍五入保留两位小数（处理计算结果）
      const roundedTotalData = totalData.map(v =>
          Math.round(v * 100) / 100 // 精确四舍五入
      );

      const series = this.chartData.map((item) => ({
        name: item.name,
        type: 'bar',
        stack: '总量',
        emphasis: {focus: 'series'},
        data: item.data.map(v => Number(v.toFixed(2))),
        label: {
          show: true,
          position: 'inside', // Placement inside the segment
          color: '#010311',  // 增加对比度
          formatter: (params) => {  // 修正参数接收方式
            const dataIndex = params.dataIndex;
            const value = params.value;
            const total = totalData[dataIndex];
            // 处理除零情况
            if (total <= 0) return '';
            // 计算显示比例
            const percentage = (value / total * 100).toFixed(1);
            return total > value ? (percentage>0 ? `${percentage}%`:'') : '100%';
          }
        },
      }));

      const totalLabelSeries = {
        type: 'bar',
        stack: '总量',
        emphasis: {focus: 'series'},
        data: roundedTotalData,
        label: {
          show: true,
          position: 'top', // Position the label at the top of the bar
          formatter: (params) => params.value.toFixed(2) , // Display the total value
          color: '#ff0000', // 设置为红色
          fontSize: 14,
          fontWeight: 'bold', // 可选：加粗显示
          offset: [0, -5],  // 关键调整：负值向上偏移
          padding: [2, 4],    // 缩小标签内边距
          backgroundColor: 'rgba(255,255,255,0.8)' // 增加背景提升可读性
        },
        itemStyle: {
          color: 'transparent',  // 完全透明
          borderWidth: 0
        },
        tooltip: { show: false }  // 禁用提示
      };

      const option = {
        grid: {
          top: '15%',
          right: '5%',
          bottom: '25%',  // 增加底部空间
          left: '10%'
        },
        tooltip: {trigger: 'item',
          barWidth: '95%',  // 控制柱子宽度
          axisPointer: { type: 'shadow' }
          },
        legend: {data: this.chartData.map(item => item.name)},
        xAxis: {type: 'category', data: this.xAxisLabels,
          axisLabel: {
            rotate: 45, // 标签旋转45度
            interval: 0, // 强制显示所有标签
            align: 'right', // 对齐方式
            margin: 8, // 标签与轴线的距离
            fontSize: 12 // 调整字体大小
          },
        },
        axisTick: {
          alignWithLabel: true // 刻度与标签对齐
        },
        yAxis: {type: 'value', axisLabel: {
            formatter: value => value.toLocaleString()
          }},
        series: [...series, totalLabelSeries],
      };

      this.myChart.setOption(option);
    },
    refreshChart() {
      this.myChart?.dispose();
      this.initChart();
    },
    handleResize() {
      this.myChart?.resize();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.myChart?.dispose();
  }
};
</script>

<style scoped>

</style>